﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Web.UI.WebControls;
using TemplateLibraryConnector.ServerControls;
using TemplateLibraryConnector.Utility;
using System.Data;

namespace TemplateLibraryConnector.UI
{
    public class SPGridViewDataSource : ObjectDataSource
    {
        //this needs to be stateless and so we need to read from ViewState what to get and recreate the List or read from session state

        private DataTable DataSource(Data.TemplateViewType templateViewType, string search, Utility.TemplateLibraryConnectorSettings settings, string sortExpression, Guid viewId)
        {
            if (settings != null)
            {
                DataTable ds = Data.TemplateLibraryFactory.GetTemplates(templateViewType, settings).GetItems(viewId);

                return Data.TemplateLibraryUtility.PerformFilter(ds, search);
            }
            else
            {
                return null;
            }
        }

        public SPGridViewDataSource()
        { }

        public DataTable SelectDataList(Data.TemplateViewType templateViewType, string search, TemplateLibraryConnectorSettings settings, string sortExpression, Guid viewId)
        {
            
            var ds = DataSource(templateViewType, search, settings, sortExpression, viewId);

            ds = this.Sort(ds, sortExpression);
            return ds;
        }

        //DataTable needed to be able to filter - convert at last moment
        public DataTable SelectData(string strTemplateViewType, string search, string strSettings, string sortExpression, string strViewId)
        {
            var settings = TemplateLibraryConnectorSettings.LoadFromString(strSettings);
            var viewId = new Guid(strViewId);
            var templateViewType = (Data.TemplateViewType)Enum.Parse(typeof(Data.TemplateViewType), strTemplateViewType, true);
            
            var ds = SelectDataList(templateViewType, search, settings, sortExpression, viewId);

            return ds;
        }
        
        private DataTable Sort(DataTable dataSource, string sortExpression)        
        {            
            //need to handle the actual sorting of the data       
            if (!string.IsNullOrEmpty(sortExpression))
            {
                return Data.TemplateLibraryUtility.SortList(dataSource, sortExpression);
            }
            else
                return dataSource;
        }  
    }
}
